// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })

exports.main = async (event, context) => {
  try {
    const db = cloud.database()
    const storyCollection = db.collection('StoryList')

    // 带ID查询逻辑
    if (event._id !== undefined) {
      const result = await storyCollection.where({
        _id: event._id
      })
      .field({  // 按需返回字段
        _id:true,
        detail: true,
        id: true,
        title: true,
        video: true,
        islike: true,
      })
      .get()

      return {
        code: 200,
        message: '查询成功',
        data: result.data[0] || null
      }
    }

    // 无参获取全部数据
    const allData = await storyCollection.get()
  
    return {
      code: 200,
      message: '获取全部数据成功',
      data: allData.data
    }

  } catch (err) {
    console.error('云函数错误:', err)
    return {
      code: 500,
      message: '服务器错误',
      data: null
    }
  }
}